package com.bridgeQQ.client.control.commands
{
	import com.bridgeQQ.client.constant.CommandConst;
	import com.bridgeQQ.client.core.ICommand;
	import com.bridgeQQ.client.events.CommandEvent;
	import com.bridgeQQ.client.model.BridgeModel;
	import com.bridgeQQ.client.vo.FriendType;
	import com.bridgeQQ.client.vo.ResultMessage;
	import com.bridgeQQ.client.vo.User;
	
	import mx.collections.ArrayCollection;
	import mx.core.Application;
	import mx.messaging.messages.IMessage;

	public class AddFriendCommand extends BaseWrapper implements ICommand
	{
		public function AddFriendCommand(respond:BaseRespond)
		{
			super(respond);
		}
		
		protected override function result(info:Object):void
		{
			var result:ResultMessage = info.respond.value;
			if(info.agree && result.result is User)
			{
				//1, produce message to fiend
				var msg:IMessage = info.msg;
				if(msg != null)
				{
					Application.application.dispatchEvent(
				    	new CommandEvent(CommandEvent.COMMAND_ACTIVATE, CommandConst.SEND_MESSAGE, 
				    	   {msg: msg}));
				}
				//2, remove exist friend in old friend type
				var types:ArrayCollection = BridgeModel.instance.possess.friendTypes;
				var type:FriendType;
				var found:Boolean;
				for(var i:int = types.length - 1; i >= 0; i--)
				{
					type = types.getItemAt(i) as FriendType;
					if(type == null)
					{
						continue;
					}
					var users:ArrayCollection = type.friends;
					for(var k:int = users.length - 1; k >= 0; k--)
					{
						if(users.getItemAt(k).email == User(result.result).email)
						{
							users.removeItemAt(k);
							found = true;
							break;
						}
					}
					if(found)
					{
						break;
					}
				}
				
				var typeID:Number = info.typeID;
				//3, Add the friend to list
				for(i = types.length - 1; i >= 0; i--)
				{
					type = types.getItemAt(i) as FriendType;
					if(type == null || type.id != typeID)
					{
						continue;
					}
					type.friends.addItem(result.result);
				}
				types.refresh();
			}
			
		}
		
		protected override function fault(info:Object):void
		{
			
		}
	}
}